//
//  YNSHomeController.m
//  HNBaseProject
//
//  Created by xujie on 2024/6/18.
//

#import "YNSHomeController.h"
#import "YNSHomeCCell.h"
#import "YNSReusableHeadView.h"
#import "YNSStartViewController.h"
#import "YNSApplePayVC.h"
#import "YNSHomeModel.h"
#import "DCMyProductionViewController.h"
#import "AppDelegate.h"
#import <AFNetworking/AFNetworking.h>
#import "NSBundle+LKLanguage.h"
#import "AIMyLibraryController.h"
#import "YNSReusableSectionView.h"
#import "YNSHomeListModel.h"
@interface YNSHomeController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)UICollectionView *collectV;
@property(nonatomic,strong)NSMutableArray*dataArray;
@property(nonatomic,copy)NSString*bgUrl;

@end

@implementation YNSHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshView) name:@"loginsuccess" object:nil];
    [self checkNet];
    [self setUI];
    self.dataArray = [[NSMutableArray alloc]init];
    [self getPic];
    [self getList];
}

#pragma mark 检查网络
- (void)checkNet
{
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
     {
         switch (status)
         {
             case AFNetworkReachabilityStatusUnknown:{

             }
                 break;
             case AFNetworkReachabilityStatusNotReachable:{
                 
             }
                 break;
             case AFNetworkReachabilityStatusReachableViaWWAN:{

                 [[AppDelegate shareDelegate] login];
             }
                 break;
             case AFNetworkReachabilityStatusReachableViaWiFi:{
                 [[AppDelegate shareDelegate] login];
             }
                 break;
             default:
                 break;
         }
     }];
    // 3.开始监听
    [manager startMonitoring];
}

- (void)refreshView {
    [self getPic];
    [self getList];
//    [self changeLang];
}

- (void)changeLang {
//    /api/user/sswitchLanguage
}
#pragma mark ---UI----
- (void)setUI{
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight+70)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    
    UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    if ([[[NSUserDefaults standardUserDefaults] objectForKey:kLanguageKey] isEqualToString:kEnglish]) {
        
        myBtn.frame = CGRectMake(kScreenW-130, kNavBarHeight+18, 114 ,27);
    } else {
        myBtn.frame = CGRectMake(kScreenW-130, kNavBarHeight+18, 114 ,27);
    }
    [myBtn setImage:[UIImage imageNamed:@"home_time"] forState:UIControlStateNormal];
    [myBtn setTitle:NSLocalizedString(@"我的制作", nil) forState:UIControlStateNormal];
    [myBtn setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
//    myBtn.backgroundColor = [UIColor blackColor];
    myBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    myBtn.layer.masksToBounds = YES;
    myBtn.layer.cornerRadius = 12;
    myBtn.layer.borderWidth = 1;
    myBtn.layer.borderColor = [UIColor colorWithHexString:@"#000000"].CGColor;
    [myBtn addTarget:self action:@selector(myBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:myBtn];
    [myBtn dc_buttonIconLeftWithSpacing:7.5];
    
    UICollectionViewFlowLayout *lay = [[UICollectionViewFlowLayout alloc]init];
    lay.itemSize = CGSizeMake((kScreenW-45)/2, (kScreenW-45)/2);
    lay.minimumLineSpacing = 15;
    lay.minimumInteritemSpacing = 15;
    lay.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
    self.collectV = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kNavBarHeight+70, kScreenW, kScreenH-kNavBarHeight-70) collectionViewLayout:lay];
    self.collectV.delegate = self;
    self.collectV.dataSource = self;
    self.collectV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectV];
    
    [self.collectV registerClass:[YNSHomeCCell class] forCellWithReuseIdentifier:@"YNSHomeCCell"];
    [self.collectV registerClass:[YNSReusableHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YNSReusableHeadView"];
    [self.collectV registerClass:[YNSReusableSectionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YNSReusableSectionView"];
}

#pragma mark----代理方法------
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    YNSHomeListModel *model = self.dataArray[section];
    return model.pics.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    YNSHomeListModel *sectioModel = self.dataArray[indexPath.section];
    YNSHomeCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YNSHomeCCell" forIndexPath:indexPath];
    YNSHomeModel*model = sectioModel.pics[indexPath.item];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DC_RequestUrl,model.pic_url]]];
    return cell;
}
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section==0)
    {
        return CGSizeMake(kScreenW, 112+kRealValue(435));
    }
    else{
        return CGSizeMake(kScreenW, 112);
    }

}
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        if (indexPath.section==0)
        {
            YNSHomeListModel *sectioModel = self.dataArray[indexPath.section];
            YNSReusableHeadView*headview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YNSReusableHeadView" forIndexPath:indexPath];
            headview.topImageV.layer.cornerRadius = 5;
            headview.topImageV.layer.masksToBounds = YES;
            headview.tLab.text = sectioModel.name;
            headview.cLab.text = sectioModel.desc;
            WEAKSELF;
            headview.startblock = ^{
                [weakSelf getMoney];
            };
            if (self.bgUrl.length>0)
            {
              [headview.topImageV  sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DC_RequestUrl,self.bgUrl]]];
            }
            return headview;
        }
        else{
            YNSHomeListModel *sectioModel = self.dataArray[indexPath.section];
            YNSReusableSectionView*sectionview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YNSReusableSectionView" forIndexPath:indexPath];
            sectionview.tLab.text = sectioModel.name;
            sectionview.cLab.text = sectioModel.desc;
            return sectionview;
        }
    }
    return nil;
}

//获取余额
- (void)getMoney {
    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/user/center" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){
            NSString *user_money = [NSString stringWithFormat:@"%@",dict[@"data"][@"user_money"]];
            if ([user_money floatValue] > 0) {
                YNSStartViewController *vc = [[YNSStartViewController alloc]init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } else {
                YNSApplePayVC *payVc = [[YNSApplePayVC alloc] init];
                [weakSelf.navigationController pushViewController:payVc animated:YES];
            }
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/user/center" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){
            NSString *user_money = [NSString stringWithFormat:@"%@",dict[@"data"][@"user_money"]];
            if ([user_money floatValue] > 0) {
                YNSHomeListModel *listModel = weakSelf.dataArray[indexPath.section];
                YNSHomeModel*model = listModel.pics[indexPath.item];
                YNSStartViewController *vc = [[YNSStartViewController alloc]init];
                vc.titleStr = [NSString stringWithFormat:@"%@",model.title];
                vc.pic_url = [NSString stringWithFormat:@"%@%@",DC_RequestUrl,model.pic_url];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } else {
                YNSApplePayVC *payVc = [[YNSApplePayVC alloc] init];
                [weakSelf.navigationController pushViewController:payVc animated:YES];
            }
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}
#pragma mark ---我的制作-----
- (void)myBtnClick {
    AIMyLibraryController *proVc = [[AIMyLibraryController alloc] init];
    [self.navigationController pushViewController:proVc animated:YES];
//    DCMyProductionViewController *proVc = [[DCMyProductionViewController alloc] init];
//    [self.navigationController pushViewController:proVc animated:YES];
}

#pragma mark-------netWorking-------
-(void)getList {
    WEAKSELF;
    
    [[DCHttpClient shareClient] requestWithPath:@"api/model_pic.model_cate/catePic" params:@{@"is_show":@"1"} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if([dict[@"code"] intValue]==1){
            [weakSelf.dataArray removeAllObjects];
            
            NSArray*arr= dict[@"data"];
            NSArray*modelArrar =  [NSArray modelArrayWithClass:[YNSHomeListModel class] json:arr];
            [weakSelf.dataArray addObjectsFromArray:modelArrar];
            [weakSelf.collectV reloadData];
        } else if ([dict[@"code"] intValue]==-1) {
            [[AppDelegate shareDelegate] login];
        }
        else {
//            [SVProgressHUD showWithStatus:dict[@"msg"]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}
//获取背景图
-(void)getPic {
    WEAKSELF;
    [[DCHttpClient shareClient] requestWithPath:@"api/model_pic.model_pic/defaultPic" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if([dict[@"code"] intValue]==1){
            weakSelf.bgUrl = [NSString stringWithFormat:@"%@",dict[@"data"][@"pic_url"]];
            [weakSelf.collectV reloadData];
        }
        else {
//            [SVProgressHUD showWithStatus:dict[@"msg"]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
